/*
Copyright (C) 2022-2024 Inspur Corp. All Rights Reserved.

SPDX-License-Identifier: Apache-2.0
*/
package main

import (
	"did-service/common/db"
	"did-service/common/logger"
	"did-service/config"
	"did-service/controller"
	"did-service/plugins/apicheck"
	"did-service/plugins/cryptoprovider"
	"did-service/plugins/sessionmgr"
	"did-service/router"
	"did-service/service"
	"net/http"
	"os"

	"github.com/emicklei/go-restful"
)

var log = logger.GetLogger("did.main")

func main() {
	container := restful.NewContainer()
	allowCors := config.Get("did.cors.allow", "true")
	if allowCors == "true" {
		cors := restful.CrossOriginResourceSharing{
			AllowedDomains: nil,
			AllowedHeaders: []string{"Origin", "Content-Length", "Content-Type", "Authorization"},
			AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"},
			CookiesAllowed: true,
			Container:      container,
		}
		container.Filter(cors.Filter)
	}

	engine := db.GetEngine()
	srv := service.NewDidService(engine)
	controller := controller.NewDidController(srv)

	router.Route(container, controller)

	port := config.Get("did.server.port", "8080")
	server := &http.Server{
		Addr:    ":" + port,
		Handler: container,
	}

	cryptoprovider.Init(config.Get("did.crypto-provider", "bcrypt"))
	sessionmgr.Init()
	apicheck.Init()
	err := server.ListenAndServe()
	defer server.Close()
	if err != nil {
		log.Errorf("server error: %s", err)
		os.Exit(1)
	}
}
